//状态
const pending = 'pending'
const fulfilled = 'fulfilled'
const rejected = 'rejected'

class Promise {
    constructor(exector) {
        this.status = pending
        this.value = undefined
        this.reason = undefined

        // 存放成功的回调
        this.onResolvedCallbacks = [];
        // 存放失败的回调
        this.onRejectedCallbacks = [];

        let resolve = (value) => {
            if (this.status == pending) {
                this.status = fulfilled
                this.value = value
                this.onRejectedCallbacks.forEach(fn => fn())
            }
        }
        let reject = (reason) => {
            if (this.status == pending) {
                this.status = reject
                this.reason = reason
                this.onRejectedCallbacks.forEach(fn => fn());
            }
        }
        try {
            exector(resolve, reject)
        } catch (error) {
            reject(error)
        }
    }

    then(onFulfilled, onRejected) {
        if (this.status === fulfilled) {
            onFulfilled(this.value)
        }
        if (this.status === rejected) {
            onRejected(this.reason)
        }
        if (this.status === pending) {
            this.onRejectedCallbacks.push(() => {
                onFulfilled(this.value)
            })
            // 如果promise的状态是 pending，需要将 onFulfilled 和 onRejected 函数存放起来，等待状态确定后，再依次将对应的函数执行
            this.onRejectedCallbacks.push(() => {
                onRejected(this.reason);
            })

        }

    }
}